package com.qqtop10.manager.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.qqtop10.manager.model.BarCode;
import com.qqtop10.manager.model.Shop;
import com.qqtop10.manager.service.AddressService;
import com.qqtop10.manager.service.BarCodeService;
import com.qqtop10.manager.service.GoodsService;
import com.qqtop10.manager.service.ShopService;
import com.qqtop10.manager.utils.FolderPath;
import com.qqtop10.manager.utils.RandomUtils;
import com.qqtop10.manager.utils.Result;
import com.qqtop10.manager.utils.oss.OSSFilePath;
import com.qqtop10.manager.utils.oss.OSSUploadUtils;

/**
 * 
 * @author Jovi
 *
 */
@RequestMapping("/manager/barCode/")
@Controller
public class BarCodeController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(BarCodeController.class);

	@Autowired
	@Qualifier("barCodeService")
	private BarCodeService barCodeService;

	@Autowired
	@Qualifier("shopService")
	private ShopService shopService;

	@Autowired
	@Qualifier("addressService")
	private AddressService addressService;

	@Autowired
	@Qualifier("goodsService")
	private GoodsService goodsService;

	/**
	 * 条件性获取封条信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getListBySelective.do")
	public void getListBySelective(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		String shop_name = request.getParameter("shop_name");
		String number = request.getParameter("number");
		Map<String, Object> map = new HashMap<>();
		StringBuffer column = new StringBuffer();
		StringBuffer from = new StringBuffer();
		StringBuffer where = new StringBuffer();
		// column
		column.append("tbc.id,tbc.uuid,tbc.shop_uuid,tbs.`name` shop_name,tbc.number,");
		column.append("tbc.goods_uuid,tbg.`name` goods_name,tbc.picture,tbc.province,tbc.city,");
		column.append("tbc.district,tbc.province_id,tbc.city_id,tbc.district_id");
		// from
		from.append("from tb_bar_code tbc");
		from.append(" INNER JOIN tb_shop tbs ON tbc.shop_uuid = tbs.uuid");
		from.append(" INNER JOIN tb_goods tbg ON tbc.goods_uuid = tbg.uuid");
		// 必须是未删除的
		where.append("WHERE tbc.isdeleted = 0 ");
		if (shop_name != null && !shop_name.trim().equals("")) {
			where.append(" AND tbc.shop_name LIKE '%" + shop_name + "%'");
		}
		if (number != null && !number.trim().equals("")) {
			where.append(" AND tbc.number = '" + number + "'");
		}
		map.put("column", column);
		map.put("from", from);
		map.put("where", where);
		map.put("order", " ORDER BY tbc.id DESC ");
		response.getWriter().print(super.page(map, barCodeService, request));
	}

	/**
	 * 条件性获取商店信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getShopList.do")
	public void getShopList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Result result = new Result();
		try {
			result.setData(shopService.selectSimple());
			result.setCode(1);
			result.setMsg("获取商店信息成功");
			logger.info("获取商店信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("获取商店信息失败：" + e.getMessage());
			logger.error(e.getMessage());
		}
		response.getWriter().print(super.result2Json(result, null));
	}

	@RequestMapping("edit.do")
	@ResponseBody
	public Result edit(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "photo", required = false) MultipartFile MFphoto, BarCode barCode) {
		Result result = new Result();
		Shop shop = null;
		try {
			shop = shopService.selectByUuid(barCode.getShop_uuid());
			if (barCode.getUuid() == null || barCode.getUuid().trim().equals("")) {
				barCode.setUuid(RandomUtils.makeUUID());
				barCode.setUuid(RandomUtils.makeUUID());
				barCode.setShop_name(shop.getName());
				barCode.setProvince(shop.getProvince());
				barCode.setCity(shop.getCity());
				barCode.setDistrict(shop.getDistrict());
				barCode.setProvince_id(shop.getProvince_id());
				barCode.setCity_id(shop.getCity_id());
				barCode.setDistrict_id(shop.getDistrict_id());
				barCode.setCreator(super.getLogindUuid());
				barCode.setCreatetime(new Date());
//				File dirFile = new File(FolderPath.getRootPath() + "/barCode/");
//				if (!dirFile.exists()) {
//					dirFile.mkdirs();
//				}
				if (MFphoto != null && !MFphoto.isEmpty()) {
					String name = MFphoto.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					String newName = barCode.getUuid() + "." + suffix;
					// 保存文件至OSS，原有的保存至本地的代码可舍弃
					OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
					// 图片上传OSS
					ossUploadUtils.uploadFile(OSSFilePath.BARCODE + newName, MFphoto);
					// 关闭OSS客户端
					ossUploadUtils.closeOssClient();
//					MFphoto.transferTo(new File(dirFile.getPath() + "/" + newName));
					barCode.setPicture(OSSFilePath.OSSDOMAIN + "/barCode/" + newName);
				}
				barCodeService.insertSelective(barCode);
			} else {
//				File dirFile = new File(FolderPath.getRootPath() + "/barCode/");
//				if (!dirFile.exists()) {
//					dirFile.mkdirs();
//				}
				if (MFphoto != null && !MFphoto.isEmpty()) {
					String name = MFphoto.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					String newName = barCode.getUuid() + "." + suffix;
					// 保存文件至OSS，原有的保存至本地的代码可舍弃
					OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
					// 图片上传OSS
					ossUploadUtils.uploadFile(OSSFilePath.BARCODE + newName, MFphoto);
					// 关闭OSS客户端
					ossUploadUtils.closeOssClient();
//					MFphoto.transferTo(new File(dirFile.getPath() + "/" + newName));
					barCode.setPicture(OSSFilePath.OSSDOMAIN + "/barCode/" + newName);
				}
				barCodeService.updateByUuidSelective(barCode);
			}
			result.setData(barCode);
			result.setCode(1);
			result.setMsg("操作封条信息成功");
			logger.info("操作封条信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("操作封条信息失败：" + e.getMessage());
			logger.error(e.getMessage());
		}
		return result;
	}

	@RequestMapping("getComboList.do")
	public void getComboList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		String callback = request.getParameter("callback");
		String shop_uuid = request.getParameter("shop_uuid");
		Result result = new Result();
		try {
			result.setCode(1);
			result.setMsg("获取商品信息成功！");
			logger.info("获取商品信息成功！");
			result.setData(goodsService.selectByShopUuid(shop_uuid));
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("获取商品信息失败：" + e.getMessage());
			logger.info("获取商品信息失败：" + e.getMessage());
		}
		response.getWriter().print(super.result2Json(result, callback));
	}
}